package spring.jdbc.db;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import spring.entity.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by kassadin@foxmail.com on 2017/5/1 0001.
 */
@Repository
public class JdbcUserRepo implements UserRepo {

    public static final String INSERT_USER = "insert into user(username,password) values(?,?)";
    public static final String SELECT_ALL = "select * from user";

    @Autowired
    private JdbcOperations jdbcOperations;

    public void addUser(User user) {
        int i = jdbcOperations.update(INSERT_USER, user.getUsername(), user.getPassword());
        System.out.println(i);
    }

    public List<User> findAll() {
        return jdbcOperations.query(SELECT_ALL, new RowMapper<User>() {
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new User(rs.getString("username"), rs.getString("password"));
            }
        });
    }
}
